package com.fxhy.filter;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.baby.constants.Constants;
import com.baby.utils.JWTUtil;
import com.fxhy.bean.AgentUser;
import com.fxhy.service.UserService;
import com.fxhy.vo.ResponseBodyEntity;

import lombok.extern.slf4j.Slf4j;

/**
 * filter过滤拦截  处理token
 * @author lifengyao
 *
 */
@Slf4j
//@Component
//@WebFilter(urlPatterns = { "/user/*" }, filterName = "tokenAuthorFilter")
public class RewriteFilter implements Filter {

	@Autowired
	private UserService userService;
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse rep = (HttpServletResponse) response;
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		
		response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        String token = req.getHeader("token");//header方式
        boolean isFilter = false;

        AgentUser user = userService.findUserByPhone(req.getHeader("phoneNum"));
        String method = ((HttpServletRequest) request).getMethod();
        if (method.equals("OPTIONS")) {
            rep.setStatus(HttpServletResponse.SC_OK);
        }else{
            if (null == token || token.isEmpty()) {
            	responseBodyEntity.setState(Constants.FAILURE);
            	responseBodyEntity.setMsg("用户授权认证没有通过!客户端请求参数中无token信息");
            } else {
                if (JWTUtil.verify(token, user.getUserId()+"", user.getLastLoginTime())) {
                	responseBodyEntity.setState(Constants.SUCCEED);
                	responseBodyEntity.setMsg("用户授权认证通过!");
                    isFilter = true;
                } else {
                	responseBodyEntity.setState(Constants.FAILURE);
                	responseBodyEntity.setMsg("用户授权认证没有通过!客户端请求参数token信息无效");
                }
            }
            if (responseBodyEntity.getState() == Constants.FAILURE) {// 验证失败
                PrintWriter writer = null;
                OutputStreamWriter osw = null;
                try {
                    osw = new OutputStreamWriter(response.getOutputStream(),
                            "UTF-8");
                    writer = new PrintWriter(osw, true);
                    String jsonStr = JSON.toJSONString(responseBodyEntity);
                    writer.write(jsonStr);
                    writer.flush();
                    writer.close();
                    osw.close();
                } catch (UnsupportedEncodingException e) {
                    log.error("过滤器返回信息失败:" + e.getMessage(), e);
                } catch (IOException e) {
                	log.error("过滤器返回信息失败:" + e.getMessage(), e);
                } finally {
                    if (null != writer) {
                        writer.close();
                    }
                    if (null != osw) {
                        osw.close();
                    }
                }
                return;
            }

            if (isFilter) {
            log.info("token filter过滤ok!");
            chain.doFilter(request, response);
            	
            }
        }
	}

	@Override
	public void destroy() {
		
	}
}
